from flask import Flask, render_template, request, flash
from static.py.SqlCommend import DB
from static.py.info import info
import random

app = Flask(__name__)
app.secret_key = "qsxcvgfdcvb:!@$%^%$<>"  # flash的密钥 自己随便写个够乱的就行
db = DB()

# name = "未登录"
# email = "无"


# 登陆界面
@app.route('/')
@app.route("/login")
@app.route("/exit")
def login():
    return render_template("login.html")


# 点击登录的响应
@app.route("/doLogin")
def doLogin():
    acc = request.args.get("uemail")  #获取账号
    pwd = request.args.get("upwd")  #获取密码
    sql = "select * from User where account =%s and password=%s"
    results = db.executeQuery(sql, [acc, pwd])
    info.name = results[0][2]
    info.email = results[0][0]
    if len(results) > 0:
        return render_template("home.html", uname=info.name,
                               uemail=info.email)  # 进入主页，提供登入账号的名字及账号
    else:
        flash("用户名或密码不正确!")  # 刷新提示
        return render_template("login.html")  # 返回登录


# 点击注册的响应
@app.route("/doRegister")
def doRegister():
    name = request.args.get("uname")
    acc = request.args.get("uemail")
    pwd = request.args.get("upwd")
    pwd2 = request.args.get("upwd2")
    if pwd != pwd2:  # 两次输入密码不同
        flash("两次输入密码不同,请重新输入!")
        return render_template("Login.html")
    sql = "select * from User where account =%s"
    results = db.executeQuery(sql, [acc])
    if len(results) > 0:  # 账号已经注册过了
        flash("该账号已注册!")
        return render_template("login.html")  # 返回登录
    else:
        sql = "insert into User values(%s,%s,%s,%s)"
        rows = db.executeUpdate(sql, [acc, pwd, name, ""])
        if rows > 0:
            flash(f"账号注册成功~")
            return render_template("login.html")  # 返回登录
        else:
            flash("注册失败!")
            return render_template("login.html")  # 返回登录


# 主页
@app.route("/home")
def home():
    return render_template("home.html", uname=info.name, uemail=info.email)


# 点击搜索法律的响应
@app.route("/getLaw")
def getLaw():
    tmp = random.randint(1, 118)  # 获取随即推荐
    sql = f"select title,id from lawCase where id>={tmp} and id<={tmp+8}"
    recommends = db.executeQuery(sql)  # 随机推荐列表

    content = request.args.get("searchLawContent")
    switchMode = request.args.get("下拉菜单")
    s = ""

    if switchMode == 'statueSearch':  # 状态搜索
        sql = "select title,statue,startdate,createdate,id from Report where statue like %s"
        s = "%"
        for i in content:
            s += (i + "%")
    elif switchMode == 'timeSearch':  # 时间搜索
        sql = "select title,statue,startdate,createdate,id from Report where startdate>=%s"
        s = content
    else:  # 题目搜索
        sql = "select title,statue,startdate,createdate,id from Report where title like %s"
        s = "%"
        for i in content:
            s += (i + "%")
    results = db.executeQuery(sql, [s])
    if len(results) > 0:
        return render_template("result.html",
                               laws=results,
                               recommends=recommends,
                               uname=info.name,
                               uemail=info.email)
    else:
        results = (["暂未搜索到想要的结果", "无", "无", "无", "#"], )
        return render_template("result.html",
                               laws=results,
                               recommends=recommends,
                               uname=info.name,
                               uemail=info.email)


# 点击对应法律跳转至内容
@app.route("/getLawContent")
def getLawContent():
    cid = request.args.get("id")
    sql = "select * from Report where id=%s"
    result = db.executeQuery(sql, [cid])
    if len(result) == 0:
        result = [0, '无', '无', '无', '无', '获取数据失败，请重试']
    ans = []
    ans.append(result[0][0])
    ans.append(result[0][1])
    ans.append(result[0][2])
    ans.append(result[0][3])
    ans.append(result[0][4])
    content = result[0][5].split('　　')
    return render_template("lawContent.html",
                           ans=ans,
                           content=content,
                           uname=info.name,
                           uemail=info.email)


# 法律案例界面
@app.route("/lawCase")  # 法律案例界面
def lawCase():
    sql = "select * from lawCase"
    results = db.executeQuery(sql)
    return render_template("lawCase.html",
                           ans=results,
                           uname=info.name,
                           uemail=info.email)


# 点击搜索法律案例的响应
@app.route("/getLawCase")
def getLawCase():
    content = request.args.get("content")  # 标题内容
    if content is None:
        return lawCase()

    s = "%"
    for i in content:
        s += (i + "%")
    sql = "select id,title,publisher,date from lawCase where title like %s"
    results = db.executeQuery(sql, [s])
    return render_template("lawCase.html",
                           ans=results,
                           uname=info.name,
                           uemail=info.email)


# 点击法律案例跳转内容
@app.route("/getLawCaseContent")
def getLawCaseContent():
    cid = request.args.get("id")
    sql = "select * from lawCase where id=%s"
    result = db.executeQuery(sql, [cid])
    ans = []
    if len(result) == 0:
        result = [0, '无', '无', '无', '获取数据失败，请重试']
    ans.append(result[0][0])
    ans.append(result[0][1])
    ans.append(result[0][2])
    ans.append(result[0][3])
    content = result[0][4].split('　　')
    return render_template("lawCaseContent.html",
                           ans=ans,
                           content=content,
                           uname=info.name,
                           uemail=info.email)


@app.route("/userpage")  # 用户个人中心
def userPage():
    sql = "select star from User where account=%s and name=%s"
    results = db.executeQuery(sql, [info.email, info.name])
    ans = []
    print(results)
    tmp = results[0][0]
    if tmp is None or tmp == '':
        ans = (["暂无收藏", "无", "无", "无", "#"], )
    else:
        tmp = tmp.split(',')
        for i in tmp:
            sql = "select title,statue,startdate,createdate,id from Report where id = %s"
            bz = db.executeQuery(sql, [i])
            ans.append(bz[0])
    # print(ans)
    return render_template("userPage.html",
                           uname=info.name,
                           uemail=info.email,
                           laws=ans)


@app.route("/addCollect", methods=['POST', 'GET'])  # 处理添加收藏
def addCollect():
    id = request.args.get("id")
    sql = "select star from User where account=%s and name=%s"
    results = db.executeQuery(sql, [info.email, info.name])
    collection = []
    print(results)
    tmp = results[0][0]
    s0 = tmp
    if (tmp is None) or (tmp == ''):
        collection.append(id)
    else:
        tmp = tmp.split(',')
        for i in tmp:
            collection.append(int(i))
        collection.append(int(id))
    collection = list(set(collection))
    collection.sort()
    s1 = f"{collection[0]}"

    for i in range(1, len(collection)):
        s1 += f",{collection[i]}"
    if s0 is not s1:
        sql = "update User set star=%s where account=%s and name=%s"
        rows = db.executeUpdate(sql, [s1, info.email, info.name])
    return getLawContent()


@app.route("/deleteStar")
def deleteStar():
    id = request.args.get("id")
    sql = "select star from User where account=%s and name=%s"
    results = db.executeQuery(sql, [info.email, info.name])
    collection = []
    tmp = results[0][0]
    tmp = tmp.split(',')
    print("tmp = ")
    print(tmp)
    print("id =")
    print(id)
    for i in tmp:
        if i != id:
            collection.append(int(i))
    if len(collection) == 0:
        sql = "update User set star=NULL where account=%s and name=%s"
        rows = db.executeUpdate(sql, [info.email, info.name])
        return userPage()
    s = f"{collection[0]}"
    for i in range(1, len(collection)):
        s += f",{collection[i]}"
    sql = "update User set star=%s where account=%s and name=%s"
    rows = db.executeUpdate(sql, [s, info.email, info.name])
    return userPage()


if __name__ == '__main__':
    app.debug = True
    app.run()
